<?php

namespace app\api\middleware;

use app\api\library\UserAuth;
use app\common\library\Code;
use Tinywan\Jwt\Exception\JwtTokenException;
use Tinywan\Jwt\Exception\JwtTokenExpiredException;
use Tinywan\Jwt\JwtToken;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AuthTokenMiddleware implements MiddlewareInterface
{
    public function process(Request $request,callable $next): Response
    {
        if ($request->method() === 'OPTIONS') {
            response( '',204 );
        }
        try {
            JwtToken::verify();
            //UserAuth::instance();
            return $next( $request );
        } catch (\Throwable $e) {
            if ($e instanceof JwtTokenExpiredException) {
                throw new JwtTokenExpiredException('登陆过期', Code::LOGIN_EXPIRED);
            }
            throw new JwtTokenException('请先登录', Code::LOST_LOGIN);
        }
    }
}